package com.chinaums.open.api.internal.util;

import com.chinaums.open.api.OpenApiContext;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User:
 * Date:
 * Time:
 * 所属模块：
 * 功能说明：Open body sig相关
 */
public class OpenBodySigUtil {

    /**
     * open-body-sig算法
     * @param context
     * @param request
     * @param method
     * @return
     */
    public static String generateSignature(OpenApiContext context, String request, String method) {

        try {
            String appId=context.getAppId();
            String appKey=context.getAppKey();
            String timestamp = new SimpleDateFormat("yyyyMMddHHmmss")
                    .format(new Date());
            String nonce = UUID.randomUUID().toString().replace("-", "");
            String testSH = DigestUtils.sha256Hex(request);

            String s1 = appId+timestamp+nonce+testSH;

            String algorithm = "HmacSHA256";
            Mac mac = Mac.getInstance(algorithm);
            mac.init(new SecretKeySpec(appKey.getBytes(), algorithm));
            byte[] localSignature =mac.doFinal(s1.getBytes("utf-8"));

            String localSignatureStr = Base64.encodeBase64String(localSignature);
            OpenApiLogger.logInfo("SHA256(签名内容):"+testSH);
            OpenApiLogger.logInfo("s1"+s1);

            if(method.equals("POST")){
                OpenApiLogger.logInfo( "OPEN-BODY-SIG AppId=" +  "\"" + appId + "\"" + ", Timestamp=" + "\"" + timestamp + "\"" + ", Nonce=" + "\"" + nonce + "\"" + ", Signature=" + "\"" + localSignatureStr + "\"");
                return "OPEN-BODY-SIG AppId=" +  "\"" + appId + "\"" + ", Timestamp=" + "\"" + timestamp + "\"" + ", Nonce=" + "\"" + nonce + "\"" + ", Signature=" + "\"" + localSignatureStr + "\"";
            }
            return "authorization=OPEN-FORM-PARAM" + "&appId=" + appId + "&timestamp=" + timestamp + "&nonce=" + nonce + "&content=" + URLEncoder.encode(request.toString(), "UTF-8") + "&signature=" + URLEncoder.encode(localSignatureStr, "UTF-8");
        } catch (Exception e) {
            OpenApiLogger.logError(e.getCause());
            return "";
        }
    }

}
